package com.itheima.consumer.controller;

import com.itheima.consumer.domain.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * Eureka Client （可以是提供者也可以是消费者）
 */
//@Controller + @ResponseBody HTTP请求获取请求体（处理复杂数据，比如JSON）
@RestController
@RequestMapping("/order") //映射路径
public class OrderController {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;


    @GetMapping("/goods/{id}")
    public Goods findGoodsById(@PathVariable("id") int id) {
        System.out.println("order"+id);

        /*
        * 通过RestTemplate远程调用goods的find接口
        * 1.首先定义一个bean RestTemplate
        * 2.把它注入到spring容器
        * 3.调用方法
        * */

        /*
        * 动态从Eureka server 注册中心中获取 provider ip和端口
        * 1.注入DiscoveryClient对象激活
        * 2.调用方法
        * */
        //discoveryClient方法,获取
        List<ServiceInstance> instances = discoveryClient.getInstances("EUREKA-PROVIDER");

        //判断集合是否有数据
        if (instances == null || instances.size() ==0){
            //如果没有数据
            return null;
        }
        ServiceInstance instance = instances.get(0);
        //获取ip
        String host = instance.getHost();
        //获取端口
        int port = instance.getPort();

        String url ="http://"+host+":"+port+"/goods/find/"+id;
        Goods goods = restTemplate.getForObject(url, Goods.class);
        return goods;
    }
}